package uit.edu.vn.Activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import uit.edu.vn.Model.myImage;
import uit.edu.vn.Utility.AESControl;
import uit.edu.vn.Utility.CheckInternet;
import uit.edu.vn.Utility.ImageListAdapter;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.httpUploader;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;


public class ImageActivity extends MyActivity{

	 /** Called when the activity is first created. */
    private Cursor myCursor;
    private ListView listview;
    private Context context;
    private TextView titleHeader;
	private ProgressDialog loadingImageDialog;
	private int numberOfItemSelected = 0;
    private final List<myImage> listImage = new ArrayList<myImage>();
   
    private AESControl aes;
    private ArrayList<myImage> itemImageCheck= new ArrayList<myImage>();
    private ImageListAdapter iAdapter;
 // private String urlString = "http://10.0.2.2:8080/ServerWeb/UploadServlet.jsp";    
    private String urlString = null;
    private String userid = "";
    private String username = "";
    private String password = "";
    private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
    private SharedPreferences ShareRef = null;	    
	private int filetype = 3;
	private Double maxSize=0.;

          
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        username = getSetting("username");
        password = getSetting("password");
        userid   = getSetting("userid");
        urlString = "http://"+ getSetting("address")+"/ServerWeb/UploadServlet.jsp";        
        
        setContentView(R.layout.backup_file);
	      //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
	      if(username.equals("") && password.equals("")){
	          Intent intent = new Intent(ImageActivity.this, LoginActivity.class);
	          startActivity(intent);
	          this.finish();            	
	      }     
	      
	        System.out.println("ImageActivity");
	        System.out.println("username: "+ username);
	        System.out.println("password: "+ password);
	        System.out.println("userid:   "+ userid);
	        System.out.println("address:   "+ urlString);	      
	      
        //thao tac voi list
        listview =(ListView)findViewById(R.id.listFileBackup);
        listview.setChoiceMode(2);
        titleHeader=(TextView)findViewById(R.id.txt_titleFile);
		titleHeader.setText(R.string.title_BackupHeaderImage);
        context=getBaseContext();
        Log.d("urlString in ImageActivity1: ", urlString);
        System.out.println(" userid in ImageActivity1: "+ userid);
        loadingImageDialog= new ProgressDialog(this);
        loadingImageDialog.setMessage(getResources().getString(R.string.dialog_message_progress));
        loadingImageDialog.setCancelable(false);
        loadingImageDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        new BackGroundTask().execute();
        listview.setOnItemClickListener(new OnItemClickListener() 
        {
     	   @Override
     	   public void onItemClick(AdapterView<?> arg0, View arg1, final int position,
 			long arg3) {
     		   
     		   	try {
     		   		showConfirmDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_mo), new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) 
						{
							// TODO Auto-generated method stub

							myImage entry = listImage.get(position);
		     		   		File temp = new File(entry.getPath());
		     		   		Intent myIntent= new Intent();
							myIntent.setAction(android.content.Intent.ACTION_VIEW);
							myIntent.setDataAndType(Uri.fromFile(temp), "image/*") ;  
							startActivity(myIntent);
						}
					});
     		   	} catch (Exception e) {
					// TODO: handle exception
					  e.printStackTrace();
				}
     		   	
     	   }
        });

    }
    
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	}    
	
	public class BackGroundTask extends AsyncTask<Void, Void, Void>  
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			 loadingImageDialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			doinBackground();		
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			loadingImageDialog.dismiss();
			iAdapter = new ImageListAdapter(context, listImage);
		    listview.setAdapter(iAdapter);
			myCursor.close();
			super.onPostExecute(result);
		}
		
	}
	private void doinBackground(){
		 //tao con tro luu database
		try {
			myCursor=this.managedQuery(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
	        startManagingCursor(myCursor);
	        while (myCursor.moveToNext())
	        {   
	        	String id= myCursor.getString(myCursor.getColumnIndexOrThrow(Images.Media._ID));
	            String imageName = myCursor.getString(myCursor.getColumnIndexOrThrow(Images.Media.DISPLAY_NAME));
	            int imageSize= myCursor.getInt(myCursor.getColumnIndexOrThrow(Images.Media.SIZE));
	            String Size=myCursor.getString(myCursor.getColumnIndexOrThrow(Images.Media.SIZE));
	    		Size= getFileSize(Size);
	            String imagePath= myCursor.getString(myCursor.getColumnIndexOrThrow(Images.Media.DATA));
	            listImage.add(new myImage(id,imageName, Size, imagePath));
	        }
	       
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
        
    
	}
	
	
    //-----------------xu lý menu------------------------------------------
	
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) 
	{
	   // TODO Auto-generated method stub
	   if(numberOfItemSelected==listImage.size())
	   {
		   menu.findItem(R.id.menu_fileSelectAll).setTitle(getResources().getString(R.string.txt_uncheckall));
	   }
	   else
	   {
		   menu.findItem(R.id.menu_fileSelectAll).setTitle(getResources().getString(R.string.txt_checkall));
		      
	   }
	return super.onMenuOpened(featureId, menu);
   }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// TODO Auto-generated method stub
    	new MenuInflater(getApplicationContext()).inflate(R.menu.backup_file_option_menu, menu);
	    return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	// TODO Auto-generated method stub
    	switch(item.getItemId())
    	{
    		case R.id.menu_fileBackup:
    			// xu ly chon file check
				//neu flag =1 thì đã có sms check roi 
				//flag=0 nghia là chưa có chon sms nao
				int flag=0;
				for(int i=0;i<listImage.size();i++)
				{
					if(listImage.get(i).getChecked()==true)
					{
					flag=1;
					numberOfItemSelected++;
					maxSize+=Double.valueOf(listImage.get(i).getSize());
					System.out.print("maxsize"+maxSize);
					}
				
				}
				if(flag==0)
				{
					numberOfItemSelected=0;
				}
    			//xu ly backup
				if(listImage.isEmpty())
				{
					showToast("Không có tập tin hình ảnh");
				}
				else
				{
					if (numberOfItemSelected==0) 
					{
						showToast(" Vui lòng chọn tập tin để sao lưu");
					}
					else
					{
						showConfirmDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_server), new OnClickListener() 
						{
							
							@Override
							public void onClick(DialogInterface dialog, int which) 
							{
								//check ketnoi internet 
								CheckInternet chkI= new CheckInternet(context);
								if (maxSize>=5)
								{
									System.out.print(maxSize);
									showAlertDialog("Thông báo","Vượt quá dung luợng cho phép , bạn chỉ được sao lưu tối đa 5 MB 1 lần", new OnClickListener() {
										
										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											
											dialog.dismiss();
										}
									});
									maxSize=0.;
								}
								else if(chkI.checkStatus().equals(true))
									{
									 
									 new BackupServerTask().execute();
							        	
									}
							        else
							        {
							        	Log.d("ketnoi", "ko co ket noi internet");
							        	showToast("Không có kết nối");						        
							        }								
							}
						});
					}
				}

    			return true;
    		case R.id.menu_fileLogout:
    			logOut();
                Intent intent = new Intent(ImageActivity.this, LoginActivity.class);
                startActivity(intent);
                this.finish();
    			return true;
    		
    		case R.id.menu_fileSelectAll:
    			//xu ly check all
    			// duyet mang item check va set true het
    			//xu ly check all
    			if(numberOfItemSelected==listImage.size())
    			{
    				// xu ly bo chon
    				for(int i=0;i<listImage.size();i++)
    				{
    					listImage.get(i).setChecked(false);
    				
    				}
    				numberOfItemSelected=0;
    			}
    			else
    			{
    				// xu ly chon
    				for(int i=0;i<listImage.size();i++)
    				{	
    					listImage.get(i).setChecked(true);
    				}
    				numberOfItemSelected=listImage.size();
    			}
    				iAdapter.notifyDataSetChanged();
    				return true;
    			}
    			
    	
    	return false;
    }
    private class BackupServerTask extends AsyncTask<Void, Void, Void>
    {
    	
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				   loadingImageDialog.setMessage(getResources().getString(R.string.dialog_message_progress_up_server));
				loadingImageDialog.show();
			}
			
			@Override
			protected Void doInBackground(Void... params) 
			{
				// TODO Auto-generated method stub
				try {
					for(int i=0;i<listImage.size();i++)
					{
						if(listImage.get(i).getChecked()==true)
						{
							myImage entry =listImage.get(i);
							itemImageCheck.add(entry);
						}
					}
					backupImageToServer(itemImageCheck);


				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				return null;
			}
			@Override
			protected void onPostExecute(Void result) 
			{
				// TODO Auto-generated method stub
				loadingImageDialog.dismiss();	
//				duyet mang và set check lai false
				for(int i=0;i<listImage.size();i++)
				{
					listImage.get(i).setChecked(false);
				}
				iAdapter.notifyDataSetChanged();
				showAlertDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_saoluuthanhcong), new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
				super.onPostExecute(result);
			}
    }
    public void backupImageToServer(ArrayList<myImage> imageBackup)
    {
        try {
        	Log.d("urlString in ImageActivity2: ", urlString);
        	System.out.println(" userid in ImageActivity2: "+ userid);
        		//thuc hien ghi du lieu len file
        	String fileName = "";
        	for(int i= 0; i<imageBackup.size(); i++)
        	{
        		File file = new File(imageBackup.get(i).getPath());
        	//	FileInputStream fis =  new FileInputStream(file);
        		Log.d("filename", file.getName()+file.getPath());
        		fileName = file.getName();
        		//xu lý mã hóa :
        		String output= imageBackup.get(i).getPath()+".aes";
        		Log.d("output",output);
        		aes = new AESControl(username);
        		aes.EncFile(imageBackup.get(i).getPath(), output);
        		
        		FileInputStream fis1= new FileInputStream(output);
				File encryptFile= new File(output);
        		String temp = String.valueOf(userid)+"@"+String.valueOf(filetype)+"@"+"sao luu tap tin anh len may chu!";
                httpUploader htfu = new httpUploader(urlString,temp, fileName);
                System.out.println("chuoi tra ve la: "+htfu.doStart(fis1));
                //xóa file mã hóa 
                encryptFile.delete();
        	} 
            //lay cac thong tin cua file gui len server de ghi len database
            //bat dau upload file len server
            //hoan tat upload file va ghi thong tin file len server
            //xoa file tam da tao tren sdcard
        	
        		
	        } catch (IOException e) {
	          System.out.println("loi khi sao luu hinh anh len may chu!"+e.toString());
	        }                
    	}
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	// TODO Auto-generated method stub
    	if(keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0){
//    		finish();
    		
    	}
    	return super.onKeyDown(keyCode, event);
    }
   }
